package com.qiaoba.auth.filter;

import com.qiaoba.api.auth.service.AuthConfigApiService;
import com.qiaoba.auth.properties.AuthConfigProperties;
import com.qiaoba.common.base.order.GlobalFilterOder;
import com.qiaoba.web.util.ResponseUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证是否是演示模式
 *
 * @author ailanyin
 * @date 2023-09-16 21:22:13
 */
@Component
@Order(GlobalFilterOder.IS_DEMO_MODE)
@RequiredArgsConstructor
public class DemoModeFilter implements Filter {

    private final AuthConfigProperties authConfigProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final AuthConfigApiService authConfigApiService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 未开启演示模式-放行
        if (!authConfigApiService.getDemoModeConfig()) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        // 白名单放行-放行
        for (String whiteUri : authConfigProperties.getWhitelist()) {
            if (antPathMatcher.match(whiteUri, uri)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        // 检查请求类型, 不是GET -> 拒绝放行
        if (!HttpMethod.GET.name().equals(request.getMethod())) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            ResponseUtil.errorAuth(response, 500, "演示模式，不允许操作");
            return;
        }
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
